const express = require('express');
const router = express.Router();
const UserService = require('../../service/user');
const _ = require('lodash');

const UserFields = ['_id', 'user_nickname','user_email','user_password','user_role','user_status'];
/**
 * 获取用户列表
 */
router.get('/list', function(req, res, next){
  const page = req.query.page || 1;
  UserService.getList(page).then( (doc) => {
    return res.json({code: 0, msg: 'success', data: doc});
  }).catch(function (err) {
    return res.json({code: -1, msg: err, data: null})
  });
})

/**
 * 新增用户
 */
router.post('/add', function(req, res, next){
  const options = _.pick(req.body,UserFields);
  UserService.add(options).then( (doc) => {
    return res.json({code: 0, msg: 'success', data: doc});
  }).catch( (err) =>{
    return res.json({code: -1, msg: err, data: null})
  });
});

/**
 * 更新用户信息
 */
router.post('/update', function(req, res, next){
  let options = _.pick(req.body,UserFields);
  options = _.omit(options,['user_password']);
  UserService.updateInfo(options).then((doc) => {
    return res.json({code: 0, msg: 'success', data: doc});
  }).catch((err)=>{
    return res.json({code: -1, msg: err, data: null})
  })
});


/**
 * 删除用户
 */
router.post('/delete', function(req, res, next){
  UserService.remove(req.body._id).then((doc)=>{
    return res.json({code: 0, msg: 'success', data: doc});
  }).catch((err)=>{
    return res.json({code: -1, msg: err, data: null})
  })
});

/**
 * 更新用户信息
 */
router.post('/froze', function(req, res, next){
  const options = {
    _id : req.body._id,
    user_status : req.body.user_status ? -1 : 0
  };
  UserService.updateInfo(options).then((doc) => {
    return res.json({code: 0, msg: 'success', data: doc});
  }).catch((err)=>{
    return res.json({code: -1, msg: err, data: null})
  })
});

module.exports = router;
